package fons.navigator.views;

import java.util.Set;

import com.google.common.collect.Sets;

import fons.model.ontology.AbstractContextDependent;
import fons.model.ontology.Context;
import fons.model.ontology.Dimension;
import fons.model.ontology.ValueSpace;

public class ViewRequirementChecker extends AbstractContextDependent {
	private final ViewRequirement requirement;
	private final Set<Dimension> dimensions = Sets.newHashSet(); 
	
	public ViewRequirementChecker(final Context context, ViewRequirement requirement) {
		super(context);
		this.requirement = requirement;
	}
	
	public boolean add (Dimension d) {
		if (checkConstraint(d)) {
			dimensions.add(d);
			return true;
		}
		return false;
	}
	
	public boolean isValid () {
		if (dimensions.isEmpty()) return requirement.optional();
		
		switch (requirement.constraint()) {
		case ALL_HAVE_VALUES: return true;
		case CROSS_HAS_VALUES: return true;
		case SOME_HAVE_VALUES:
			for (Dimension d: dimensions) if (d.getValues().size() > 0) return true;
			return false;
			
		default:
		case NONE:
			return true;
		}
	}
	
	public Set<Dimension> get() {
		return isValid() ? dimensions : null; 
	}
	
	private boolean checkConstraint (Dimension candidate) {
		switch (requirement.constraint()) {
		case ALL_HAVE_VALUES: return candidate.getValues().size() > 0;
		case CROSS_HAS_VALUES: 
			return ValueSpace.of(dimensions).subSpace(candidate).getValues().size() > 0;
		case SOME_HAVE_VALUES:
			
		default:
		case NONE:
			return true;
		}
	}
}
